<template>
    <div class="e-table">
        <div class="top" v-if="!isView">
            <div class="left">
                <el-upload
                    class="upload-demo"
                    :action="uploadUrl"
                    :headers="{
                        token: userInfo.token,
                        org: encodeURIComponent(JSON.stringify(userInfo.orgInfo))
                    }"
                    :data="{
                        bucketName,
                        relationId,
                        relationTag,
                        orgCode
                    }"
                    :before-upload="beforeAvatarUpload"
                    multiple
                    :accept="accept"
                    :on-success="attachOnSuccess"
                    :show-file-list="false"
                    name="files"
                >
                    <el-button size="mini" class="btn-blue">
                        上传附件
                    </el-button>
                </el-upload>
                <el-button
                    size="mini"
                    class="btn-blue"
                    @click="attachDownload"
                    v-if="attachSelection.length>0"
                    >批量下载</el-button
                >
                <el-button
                    slot="reference"
                    size="mini"
                    class="btn-delete"
                    v-if="attachSelection.length>0"
                    @click="deleteData"
                    >批量删除</el-button
                >
                <span style="margin: 0 0 0 10px; color: #999; line-height: 35px"
                >*温馨提示:租赁验收需要上传影像资料《包括整车照片、主动力铭牌、整车铭牌等重要参数的》照片，如果有特种设备，则还需要上传合格证。</span>
            </div>
        </div>
        <div class="top" v-if="isView">
            <div class="left">
                <el-button
                    size="mini"
                    class="btn-blue"
                    @click="attachDownload"
                    v-if="attachSelection.length>0"
                    >批量下载</el-button
                >
                <span style="margin: 0 0 0 10px; color: #999; line-height: 35px"
                >*温馨提示:租赁验收需要上传影像资料《包括整车照片、主动力铭牌、整车铭牌等重要参数的》照片，如果有特种设备，则还需要上传合格证。</span>
            </div>
        </div>
        <el-table
            :max-height="$store.state.tableHeight"
            class="table"
            :data="attachTableData"
            border
            style="width: 100%"
            ref="table"
            @selection-change="attachSelectionChange"
            v-sortTable="{ 'tableData': attachTableData, '_this': this, 'ref': 'table' }"
        >
            <el-table-column show-overflow-tooltip type="selection" width="55">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="objectPath" min-width="200" label="缩略图">
                <template slot-scope="{ row }" :size="60">
                    <el-image
                        v-if="'jpg,jpeg,png'.includes(row.objectName.split('.').pop().toLowerCase())"
                        style="width: 30px; height: 30px"
                        :src="row.objectPath"
                        :preview-src-list="imageList"
                    ></el-image>
                    <el-image v-else style="width: 100px; height: 100px" :src="pdfImg"></el-image>
                </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="objectName" min-width="200" label="文件名称">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="objectSize" label="文件大小" width="150">
                <template slot-scope="{ row }">
                    {{ bytesToSize(row.objectSize) }}
                </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="gmtCreate" min-width="200" label="上传时间">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="userName" min-width="150" label="上传人">
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import ossRequest from '@/api/oss/oss.js'
import { oss } from '@/utils/request'
import pdfImg from '@/assets/pdf_icon.png'
import { bytesToSize, showLoading, hideLoading, batchDownload } from '@/utils/common'
//import requestDown from '@/api/equip/attachDown'
import service from '@/utils/request'
export default {
    data () {
        return {
            oss: oss,
            uploadUrl: 'api/oss/uploader',
            accept: '.jpg,jpeg,.png,.pdf',
            attachTableData: [],
            attachSelection: [],
            relationId: JSON.parse(localStorage.vuex).auditParams.billid, //关联id1
            relationTag: JSON.parse(localStorage.vuex).auditParams.id, //关联id2
            pdfImg,
            isView: JSON.parse(localStorage.vuex).auditParams.isView, //是查看还是编辑页面
        }
    },
    created () {
        this.getObjectByRelationId()
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
        }),
        orgCode () {
            return this.$store.state.userInfo.orgInfo.shortCode
        },
        bucketName () {
            return 'facilityconnect'
        },
        imageList () {
            return this.attachTableData.filter(row=>'jpg,jpeg,png'.includes(row.objectName.split('.').pop().toLowerCase())).map(x=>oss + x.nonIPObjectPath)
        }
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //文件大小
        bytesToSize (byte) {
            return bytesToSize(byte)
        },
        beforeAvatarUpload (file) {
            const isLt2M = file.size / 1024 / 1024 < 20
            if (!isLt2M) {
                this.clientPop('err', '上传文件大小不能超过 20MB！')
            }
            return isLt2M
        },
        //上传成功
        attachOnSuccess () {
            this.getObjectByRelationId()
        },
        //获取上传的对象
        getObjectByRelationId () {
            if (!this.relationId) return
            return ossRequest.getObjectByRelationId({ relationId: this.relationId }).then(res => {
                this.attachTableData = []
                res.map(x=>{
                    if(x.relationIdTag === this.relationTag) {
                        this.attachTableData.push(x)
                    }
                })
            })
        },
        //获取选中的项
        attachSelectionChange (selection) {
            this.attachSelection = selection
        },
        deleteData () {
            const length = this.attachSelection.length
            this.clientPop(
                'info',
                `已选择【${length}】条数据，确定要删除吗？数据删除后不可恢复，请谨慎操作！`,
                this.attachDel
            )
        },
        attachDel () {
            const recordIds = this.attachSelection.map(value => value.recordId)
            const promiseArr = []
            showLoading()
            recordIds.forEach(value => {
                promiseArr.push(ossRequest.deleterRecordId({ recordId: value }))
            })
            Promise.all(promiseArr)
                .then(() => {
                    this.clientPop('suc', '删除成功', this.getObjectByRelationId)
                })
                .catch(() => {
                    this.clientPop('err', '部分数据删除失败', this.getObjectByRelationId)
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //批量下载
        attachDownload () {
            const fileList = this.attachSelection.map(item=>{
                return {
                    objectName: item.objectName,
                    objectPath: item.objectPath
                }
            })
            batchDownload(fileList)
        },
        autoClick ({ fileName, url }) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = url
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
        },
        dataURLtoBlob (dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = window.atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new Blob([u8arr], { type: mime })
        },
        downloadIamge (imgsrc, fileName) {
            //下载图片地址和图片名
            var image = new Image()
            // 解决跨域 Canvas 污染问题
            image.setAttribute('crossOrigin', 'anonymous')
            image.onload = function () {
                const canvas = document.createElement('canvas')
                canvas.width = image.width
                canvas.height = image.height
                const context = canvas.getContext('2d')
                context.drawImage(image, 0, 0, image.width, image.height)
                const _dataURL = canvas.toDataURL('image/png') //得到图片的base64编码数据

                const blob_ = this.dataURLtoBlob(_dataURL) // 用到Blob是因为图片文件过大时，在一部风浏览器上会下载失败，而Blob就不会

                const url = {
                    name: fileName || '图片.png', // 图片名称不需要加.png后缀名
                    src: blob_
                }

                if (window.navigator.msSaveOrOpenBlob) {   // if browser is IE
                    navigator.msSaveBlob(url.src, url.name)//filename文件名包括扩展名，下载路径为浏览器默认路径
                } else {
                    this.autoClick({
                        fileName: url.name,
                        url: window.URL.createObjectURL(url.src)
                    })
                }
            }.bind(this)
            image.src = imgsrc
        },
        async downloadFile (obj) {
            const url = oss +  obj.nonIPObjectPath
            const fileNameFull = obj.originalObjectName
            const fileExt = fileNameFull.split('.').pop()
            if (['jpg', 'jpeg', 'gif', 'png', 'bmp'].indexOf(fileExt.toLowerCase()) === -1) {
                const { httpGetFile } = service
                const data = await httpGetFile({ url })
                const blob = new Blob([data])
                const reader = new FileReader()
                reader.readAsDataURL(blob)
                reader.onload = function (e) {
                    this.autoClick({
                        fileName: fileNameFull,
                        url: e.target.result
                    })
                }.bind(this)
            } else {
                this.downloadIamge(url, fileNameFull)
            }
        },
    },
}
</script>

<style lang="sass" scoped></style>
